package com.flute.tools.util.performance;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;

import com.flute.tools.util.StringUtil;

public class UrlSet {
	private HashSet<String> urls;

	public UrlSet() {
		this.urls = new LinkedHashSet<String>();
	}

	public void addUrl(String url) {
		this.urls.add(url);
	}

	public Iterator<String> getUrls() {
		return urls.iterator();
	}

	public static List<String> urlListFromFile(String fileName) {
		List<String> list = new ArrayList<String>();
		BufferedReader reader;
		FileInputStream stream;

		try {
			stream = new FileInputStream(new File(fileName));
			reader = new BufferedReader(new InputStreamReader(stream, "utf8"));

			while (reader.ready()) {
				String line = reader.readLine();
				if (!StringUtil.isNullOrEmpty(line) && line.startsWith("http")) {
					list.add(line);
				}
			}
			
			reader.close();
			stream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return list;
	}

	public static Iterator<String> UrlSetFromFile(final String fileName) {
		return new Iterator<String>() {

			private BufferedReader reader;
			private FileInputStream stream;

			{
				try {
					this.stream = new FileInputStream(new File(fileName));
					this.reader = new BufferedReader(new InputStreamReader(
							stream, "utf8"));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public boolean hasNext() {

				boolean hasNext = false;
				try {
					hasNext = reader.ready();
					if (!hasNext) {
						reader.close();
						stream.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}

				return hasNext;
			}

			@Override
			public String next() {
				String line;
				try {
					line = reader.readLine();
					if (StringUtil.isNullOrEmpty(line)) {
						line = "";
					}

					return line;
				} catch (IOException e) {
					e.printStackTrace();
				}

				return "";
			}

			@Override
			public void remove() {
			}

		};
	}
}
